//Copyright (c) 2010 Jimmy Merari - jim.merari@gmail.com

//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:

//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.

//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.

using System;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using DotNetNuke.Entities.Modules;

using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Entities.Users;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Services.Tokens;
using DotNetNuke.Services.Exceptions;

namespace Cinovasi.Scriptagility
{
    public partial class View : PortalModuleBase, IActionable
    {
        #region IActionable Members

        public DotNetNuke.Entities.Modules.Actions.ModuleActionCollection ModuleActions
        {
            get
            {
                ModuleActionCollection actions = new ModuleActionCollection();

                string strEditor = ResolveUrl(ModulePath);
                string targetPath = strEditor + "ScriptEditor.aspx?moduleId=" + ModuleId.ToString() + "&tabId=" + TabId.ToString();
                actions.Add(GetNextActionID(), "Script Editor", ModuleActionType.AddContent, "", "", targetPath, false,
                    DotNetNuke.Security.SecurityAccessLevel.Admin, true, false);
                return actions;
            }
        }

        #endregion

        protected void Page_Init(object sender, EventArgs e)
        {
            try
            {
                RenderScript();
            }
            catch (Exception exc)
            {
                Exceptions.ProcessModuleLoadException(this, exc);

            }

        }


        private void RenderScript()
        {
            ArrayList scripts = ScriptInfo.GetScriptByModuleId(ModuleId);
            TokenReplace tr = new TokenReplace(Scope.Debug);
            tr.User = UserController.GetCurrentUserInfo();
            ModuleController mc = new ModuleController();
            tr.ModuleInfo = mc.GetModule(ModuleId, TabId);
            tr.ModuleId = ModuleId;
            tr.PortalSettings = PortalSettings;

            StringBuilder sbHead = new StringBuilder();
            StringBuilder sbUpper = new StringBuilder();
            StringBuilder sbInplace = new StringBuilder();
            StringBuilder sbLower = new StringBuilder();

            foreach (ScriptInfo info in scripts)
            {
                if (info.Script.Length == 0) continue;
                if (info.Placement == ScriptInfo.EPlacement.External || info.Placement == ScriptInfo.EPlacement.Disabled) continue;
                string name = "\n<!--Scriptagility" + ModuleId.ToString() + info.ScriptName + "-->\n";

                string replaced = info.Script;
                if (info.EnableTokenReplace)
                {
                    replaced = tr.ReplaceEnvironmentTokens(info.Script);
                    replaced = replaced.Replace("{{SYS:AppRoot}}", Request.ApplicationPath);
                }
                
                switch (info.Placement)
                {
                    case ScriptInfo.EPlacement.Head:
                        {
                            sbHead.AppendLine(name);
                            sbHead.AppendLine(replaced);
                        }
                        break;
                    case ScriptInfo.EPlacement.Upper:
                        {
                            sbUpper.AppendLine(name);
                            sbUpper.AppendLine(replaced);
                        }
                        break;
                    case ScriptInfo.EPlacement.InPlace:
                        {
                            sbInplace.AppendLine(name);
                            sbInplace.AppendLine(replaced);
                        }
                        break;
                    case ScriptInfo.EPlacement.Lower:
                        {
                            sbLower.AppendLine(name);
                            sbLower.AppendLine(replaced);
                        }
                        break;
                }
            }

            string head = sbHead.ToString();
            if (head.Length != 0)
            {
                Literal script = new Literal();
                script.Text = head;
                Page.Header.Controls.Add(script);
            }

            string upper = sbUpper.ToString();
            if (upper.Length != 0)
            {
                Control body = this.Page.FindControl("body");
                if (body != null)
                {
                    Literal script = new Literal();
                    script.Text = upper;
                    body.Controls.AddAt(0, script);
                }

            }

            string inplace = sbInplace.ToString();
            if (inplace.Length != 0)
            {
                Literal script = new Literal();
                script.Text = inplace;
                this.Controls.Add(script);

            }

            string lower = sbLower.ToString();
            if(lower.Length != 0)
            {
                Control body = this.Page.FindControl("body");
                if (body != null)
                {
                    Literal script = new Literal();
                    script.Text = lower;
                    body.Controls.Add(script);
                }
            }
        }



#if false

        protected void CreateAppInfo(UserInfo currentUser)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<script type=\"text/javascript\">");
            sb.AppendFormat("var Scripter{0}AppInfo = {{", ModuleId);
            sb.AppendFormat("\"appPath\":'{0}',", Request.ApplicationPath);
            sb.AppendFormat("\"modulePath\":'{0}',", ModulePath);
            sb.AppendFormat("\"moduleId\":{0},", ModuleId);
            sb.AppendFormat("\"tabId\":{0},", TabId);
            sb.AppendFormat("\"tabModuleId\":{0},", TabModuleId);
            sb.AppendFormat("\"homeTabId\":{0},", PortalController.GetCurrentPortalSettings().HomeTabId);
            sb.AppendFormat("\"userId\":{0},", UserId);
            if (currentUser != null)
            {
                sb.AppendFormat("\"userName\":'{0}',", GetSingleQuoteSafeText(currentUser.Username));
                sb.AppendFormat("\"userDisplayName\":'{0}',", GetSingleQuoteSafeText(currentUser.DisplayName));
            }
            else
            {
                sb.Append("\"userName\":'',");
                sb.Append("\"userDisplayName\":'',");
            }

        RoleController rc = new RoleController();
            ArrayList roles = rc.GetUserRoles(this.PortalId, this.UserId);
            StringBuilder strRole = new StringBuilder();
            bool firstRole = true;
            strRole.Append("[");
            foreach (UserRoleInfo uri in roles)
            {
                if (firstRole) firstRole = false;
                else strRole.Append(",");
                strRole.AppendFormat("'{0}'", uri.RoleName);
            }
            strRole.Append("]");
            sb.AppendFormat("\"userRoles\":{0}", strRole.ToString());
            sb.Append("\"userRoles\":[]");
            sb.Append("};");
            sb.Append("</script>");

            Literal ltAppInfo = new Literal();
            ltAppInfo.Text = sb.ToString();
            Page.Header.Controls.Add(ltAppInfo);
        }

        public string GetSingleQuoteSafeText(string sText)
        {
            if (sText != null)
            {
                sText = sText.Replace("'", "\\'");
                sText = sText.Replace("\n", "\\n");
            }
            else
                sText = "";
            return sText;
        }
#endif

    }
}